package com.two.screen.water.balance.widget.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.MyTextWatcher
import com.two.screen.water.balance.bean.database.OrderProductDB
import com.two.screen.water.balance.image.ImageManger
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.utils.DialogUtil
import com.two.screen.water.balance.utils.ToastUtil
import com.two.screen.water.balance.widget.keyboard.edit_order.KeyboardUtilEditOrder
import com.two.screen.water.balance.widget.keyboard.edit_order.MyKeyBoardViewEditOrder

//编辑计重
class EditOrderGoodsWeightInfoDialog(var mContext: Context) : Dialog(mContext, R.style.ChooseDialog) {

    private var mEditGoodsInfoDialogListener: EditGoodsInfoDialogListener? = null
    private var mWeightOrTimesEt: EditText? = null
    private var mNowPriceEt: EditText? = null
    private var mDiscountPercentEt: EditText? = null
    private var mSubTotalPriceTv: TextView? = null
    private var mConfirmTv: TextView? = null
    private var mDialogIv: ImageView? = null
    private var mDialogProductTv: TextView? = null
    private var mSalePriceTv: TextView? = null
    private var mOnTimesTv: TextView? = null
    private var mOnWeightTv: TextView? = null
    private var mIsWeightLayout: View? = null


    //private var mWeightType = 0//读取称重数据：0;  手动输入：1
    private var mUnitType = 0//称重模式0；计件模式1
    private var mPriceBefore: String? = null


    private var mMyKeyBoardViewEditOrder: MyKeyBoardViewEditOrder? = null
    private var mKeyboardUtilEditOrder: KeyboardUtilEditOrder? = null
    private var imm: InputMethodManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_edit_goods_info_weight)
        this.setCanceledOnTouchOutside(false)

        val window = window
        if (window != null) {
            val attributes = window.attributes
            attributes.width = App.screenWidth
            window.attributes = attributes
            window.setGravity(Gravity.CENTER)
        }

        mWeightOrTimesEt = findViewById(R.id.mWeightOrTimesEt)
        mNowPriceEt = findViewById(R.id.mNowPriceEt)
        mDiscountPercentEt = findViewById(R.id.mDiscountPercentEt)
        mSubTotalPriceTv = findViewById(R.id.mSubTotalPriceTv)
        mConfirmTv = findViewById(R.id.mConfirmTv)
        mMyKeyBoardViewEditOrder = findViewById(R.id.keyboard_view)
        mDialogIv = findViewById(R.id.mDialogIv)
        mDialogProductTv = findViewById(R.id.mDialogProductTv)
        mSalePriceTv = findViewById(R.id.mSalePriceTv)
        mOnTimesTv = findViewById(R.id.mOnTimesTv)
        mOnWeightTv = findViewById(R.id.mOnWeightTv)
        mIsWeightLayout = findViewById(R.id.mIsWeightLayout)

        //mIsWeightLayout?.visibility = if (DataApi.mIsWeight) View.VISIBLE else View.GONE

        findViewById<View>(R.id.mCloseIv).setOnClickListener { dismiss() }
        findViewById<View>(R.id.dialog_root).apply {
            setOnClickListener {
                dismiss()
            }
        }
        findViewById<View>(R.id.mContentLayout).apply {
            setOnClickListener {
            }
        }

        mOnWeightTv?.setOnClickListener {
            mOnTimesTv?.isSelected = false
            mOnWeightTv?.isSelected = true
            mUnitType = 0
            initKeyboard()
        }
        mOnTimesTv?.setOnClickListener {
            mOnWeightTv?.isSelected = false
            mOnTimesTv?.isSelected = true
            mUnitType = 1
            initKeyboard()
        }
        hideSoftKeyBoard()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initKeyboard() {
        if (mKeyboardUtilEditOrder == null) mKeyboardUtilEditOrder = KeyboardUtilEditOrder(mContext as Activity, mMyKeyBoardViewEditOrder)
        //这里还需要考虑处理
        if (mUnitType == 0) { //计重模式
            //是否 允许可以修改重量
            if (DataApi.mIsWeight) {
                //允许
                mWeightOrTimesEt?.isEnabled = true
                mWeightOrTimesEt?.requestFocus()
                mNowPriceEt?.clearFocus()
                mWeightOrTimesEt?.setSelectAllOnFocus(true)
                mWeightOrTimesEt?.selectAll()
                mKeyboardUtilEditOrder?.attachTo(mWeightOrTimesEt)
            } else {
                //不允许
                mWeightOrTimesEt?.isEnabled = false
                mWeightOrTimesEt?.clearFocus()
                mNowPriceEt?.requestFocus()
                mNowPriceEt?.setSelectAllOnFocus(true)
                //mNowPriceEt?.requestFocus()
                mNowPriceEt?.selectAll()
                mKeyboardUtilEditOrder?.attachTo(mNowPriceEt)
            }
        } else { //计件模式
            mWeightOrTimesEt?.setText(mItem?.weight ?: "1")
            mWeightOrTimesEt?.isEnabled = true
            mWeightOrTimesEt?.requestFocus()
            mNowPriceEt?.clearFocus()
            mWeightOrTimesEt?.setSelectAllOnFocus(true)
            mWeightOrTimesEt?.selectAll()
            mKeyboardUtilEditOrder?.attachTo(mWeightOrTimesEt)
        }
        mWeightOrTimesEt?.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_UP) {
                mKeyboardUtilEditOrder?.attachTo(mWeightOrTimesEt)
            }
            false
        }
        mNowPriceEt?.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_UP) {
                mKeyboardUtilEditOrder?.attachTo(mNowPriceEt)
            }
            false
        }
        mDiscountPercentEt?.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_UP) {
                mKeyboardUtilEditOrder?.attachTo(mDiscountPercentEt)
            }
            false
        }
    }

    private var mItem: OrderProductDB? = null
    fun setGoodsInfo(item: OrderProductDB) {
        mItem = item

        //初始化称重状态
        mUnitType = item.unitType
        if (mUnitType == 1) {
            mOnTimesTv?.isSelected = true
            mOnWeightTv?.isSelected = false
        } else {
            mOnTimesTv?.isSelected = false
            mOnWeightTv?.isSelected = true
        }
        mPriceBefore = String.format("%.2f", item.realPrice?.toDouble() ?: "0.00")

        //初始化数据
        mDialogProductTv?.text = item.productName
        mWeightOrTimesEt?.setText(item.weight)
        mSalePriceTv?.text = item.oriPrice
        mNowPriceEt?.setText(item.realPrice)
        mDiscountPercentEt?.setText(item.discountPercent.toString())//创建好数据库，使用那边赋值
        mSubTotalPriceTv?.text = item.subTotalPrice

        //菜品图
        mDialogIv?.let {
            if (item.logoImage.isNullOrBlank()) it.setImageResource(R.drawable.default_food) else ImageManger.setCenterCropImg(context, item.logoImage, it)
        }

        mConfirmTv?.setOnClickListener {
            var nowPrice = try {
                mNowPriceEt?.text?.toString()?.toDouble() ?: 0.0
            } catch (e: Exception) {
                0.0
            }
            var discountPercent = try {
                mDiscountPercentEt?.text?.toString()?.toInt() ?: 100
            } catch (e: Exception) {
                100
            }

            var weight = try {
                mWeightOrTimesEt?.text?.toString()?.toDouble() ?: 0.0
            } catch (e: Exception) {
                0.0
            }

            var subTotalPrice = try {
                mSubTotalPriceTv?.text?.toString()?.toDouble()
            } catch (e: Exception) {
                0.0
            }
            if (weight == 0.0) {
                ToastUtil.showToast(if (mUnitType == 0) "重量不能为0" else "数量不能为0")
                return@setOnClickListener
            }

            item.realPrice = String.format("%.2f", nowPrice)
            item.weight = String.format("%.3f", weight)
            item.subTotalPrice = String.format("%.2f", subTotalPrice)
            item.discountPercent = discountPercent
            //CommUtils.println("First update->", "mPriceBefore:$mPriceBefore,realPrice:${item.realPrice};;mUnitType:$mUnitType,unitType:${item.unitType}")
            //TODO:这里还可能计算优惠金额
            item.giftPrice = String.format("%.2f", nowPrice * (100 - discountPercent) / 100.0 * weight)
            var isSameUnitType = mUnitType == item.unitType
            item.unitType = mUnitType
            mEditGoodsInfoDialogListener?.onConfirm(item, mPriceBefore == item.realPrice && isSameUnitType)
            dismiss()
        }

        //数字键盘监听
//        mKeyboardUtilEditOrder?.setOnKeyBoardEditOrderListener {
//            var nowPrice = try {
//                mNowPriceEt?.text?.toString()?.toDouble() ?: 0.0
//            } catch (e: Exception) {
//                0.0
//            }
//            var weight = try {
//                mWeightEt?.text?.toString()?.toDouble() ?: 0.0
//            } catch (e: Exception) {
//                0.0
//            }
//
//            var newSubTotalPrice = nowPrice * weight
//            //重新统计 小计
//            item.subTotalPrice = String.format("%.2f", newSubTotalPrice)
//            mSubTotalPriceTv?.text = item.subTotalPrice
//        }
        addNowPriceEtTextChangedListener?.let { mNowPriceEt?.removeTextChangedListener(it) }
        addNowPriceEtTextChangedListener = null
        addNowPriceEtTextChangedListener = object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                updateSubTotalPriceEt(item)
            }
        }
        mNowPriceEt?.addTextChangedListener(addNowPriceEtTextChangedListener)

        addDiscountPercentEtTextChangedListener?.let { mDiscountPercentEt?.removeTextChangedListener(it) }
        addDiscountPercentEtTextChangedListener = null
        addDiscountPercentEtTextChangedListener = object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                //处理>=100
                //CommUtils.println("DiscountPercent->", s.toString())
                var discountPercent = try {
                    mDiscountPercentEt?.text?.toString()?.toInt() ?: 100
                } catch (e: Exception) {
                    100
                }
                if (discountPercent > 100) {
                    mDiscountPercentEt?.setText("100")
                    mDiscountPercentEt?.selectAll()
                }
                updateSubTotalPriceEt(item)
            }
        }
        mDiscountPercentEt?.addTextChangedListener(addDiscountPercentEtTextChangedListener)


        addWeightEtTextChangedListener?.let { mWeightOrTimesEt?.removeTextChangedListener(it) }
        addWeightEtTextChangedListener = null
        addWeightEtTextChangedListener = object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                updateSubTotalPriceEt(item)
            }
        }
        mWeightOrTimesEt?.addTextChangedListener(addWeightEtTextChangedListener)
        initKeyboard()
        mWeightOrTimesEt?.postDelayed({
            hideSoftKeyBoard()
        }, 500)
    }

    private var addDiscountPercentEtTextChangedListener: MyTextWatcher? = null
    private var addNowPriceEtTextChangedListener: MyTextWatcher? = null
    private var addWeightEtTextChangedListener: MyTextWatcher? = null

    private fun updateSubTotalPriceEt(item: OrderProductDB) {
        hideSoftKeyBoard()
        var nowPrice = try {
            mNowPriceEt?.text?.toString()?.toDouble() ?: 0.0
        } catch (e: Exception) {
            0.0
        }
        var discountPercent = try {
            mDiscountPercentEt?.text?.toString()?.toInt() ?: 100
        } catch (e: Exception) {
            100
        }
        var weight = try {
            mWeightOrTimesEt?.text?.toString()?.toDouble() ?: 0.0
        } catch (e: Exception) {
            0.0
        }

        var newSubTotalPrice = nowPrice * weight * (discountPercent / 100.0)
        //重新统计 小计
        item.subTotalPrice = String.format("%.2f", newSubTotalPrice)
        mSubTotalPriceTv?.text = item.subTotalPrice
    }

    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (this.imm == null) {
            this.imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && this.imm != null) {
            this.imm!!.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

    fun setEditGoodsInfoListener(l: EditGoodsInfoDialogListener) {
        mEditGoodsInfoDialogListener = l
    }

    fun setWeightData(weightStr: String?) {
        if (mUnitType == 0 && !DataApi.mIsWeight) {
            mWeightOrTimesEt?.setText(weightStr)
        }
    }


    interface EditGoodsInfoDialogListener {
        fun onConfirm(item: OrderProductDB, mIsSamePrice: Boolean)
    }

    override fun dismiss() {
        addDiscountPercentEtTextChangedListener?.let { mDiscountPercentEt?.removeTextChangedListener(it) }
        addNowPriceEtTextChangedListener?.let { mNowPriceEt?.removeTextChangedListener(it) }
        addWeightEtTextChangedListener?.let { mWeightOrTimesEt?.removeTextChangedListener(it) }
        addNowPriceEtTextChangedListener = null
        addWeightEtTextChangedListener = null
        super.dismiss()
    }

    override fun show() {
        super.show()
        //隐藏状态栏
        window?.let { DialogUtil.hideNavigationBar(it) }
    }
}
